package Server;

import javax.swing.*;
import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.List;

class SocketServer extends JFrame 
{
	private int HOST_PORT = 3200;
	private ServerSocket server = null;
	public static List<ClientWorker> listClientWorker = new ArrayList<ClientWorker>();
	public static int ID = 0;
	
	/**
	 * Khởi tạo SocketServer
	 * @param Frame của ServerGUI
	 * @throws IOException
	 */
	SocketServer(ServerGUI fatherFrame) throws IOException {		
		try
		{
			server = new ServerSocket(HOST_PORT);
			
			do
			{
				ClientWorker cw;
				Socket client;
				BufferedReader br;
				BufferedWriter bw;
				try
				{
					ID++;
					client = server.accept();
					br = new BufferedReader(new InputStreamReader(client.getInputStream()));
					bw = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
					cw = new ClientWorker(client, fatherFrame,br,bw,ID);
					listClientWorker.add(cw);
					Thread t = new Thread(cw);
					t.start();
				}
				catch (IOException e)
				{
					JOptionPane.showMessageDialog(this, e.toString(), "Lỗi kết nối",
							JOptionPane.WARNING_MESSAGE);
				}
			}
			while (true);
		}
		catch(IOException e)
		{
			JOptionPane.showMessageDialog(this, e.toString(), "Lỗi kết nối", JOptionPane.WARNING_MESSAGE);
		}
	}
	
	public void ngatKetNoiClientID(int _id) throws IOException
	{
		for (int i = 0; i < listClientWorker.size(); i++)
		{
			if (listClientWorker.get(i).id == _id)
			{
				listClientWorker.get(i).ngatKetNoi();
			}
		}
	}

	/**
	 * Đóng kết nối.
	 */
	protected void finalize() {
		try {
			server.close();
		} catch (IOException e) {
			JOptionPane.showMessageDialog(this, e.toString(), "Lỗi đóng kết nối", JOptionPane.ERROR_MESSAGE);
			System.exit(-1);
		}
		
	}	
}